package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();

        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {
//			for (CartProductDto cartProductDto : cartProductDtoList) {
//				buyProductIds.add(cartProductDto.getProductId());
//			}
            buyProductIds = cartProductDtoList.stream().map(CartProductDto::getProductId).collect(Collectors.toList());
        }
        HashSet<Long> set = new HashSet<>(buyProductIds);
        buyProductIds = new ArrayList<>(set);
        buyProductIds.sort(Long::compareTo);

        // 锁定库存
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);

        if (CollectionUtils.isEmpty(stocksForUpdate)) {
            throw new BizException(OrderRetCode.STOCK_ALL_LOCKING_FAILED.getCode(), OrderRetCode.STOCK_ALL_LOCKING_FAILED.getMessage());
        }

        if (stocksForUpdate.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.STOCK_PART_LOCKING_FAILED.getCode(), OrderRetCode.STOCK_PART_LOCKING_FAILED.getMessage());
        }

        // 下面是为了找到用户以前购买过的商品以及数量
        Example orderMapperExample = new Example(Order.class);
        orderMapperExample.createCriteria().andEqualTo("userId", createOrderContext.getUserId());
        List<Order> orders = orderMapper.selectByExample(orderMapperExample);

        ArrayList<String> orderIdList = new ArrayList<>();
        for (Order order : orders) {
            String orderId = order.getOrderId();
            orderIdList.add(orderId);
        }
        List<OrderItem> orderItems;
        if (orderIdList.size() != 0) {
            Example orderItemMapperExample = new Example(OrderItem.class);
            orderItemMapperExample.createCriteria().andIn("orderId", orderIdList);
            orderItems = orderItemMapper.selectByExample(orderItemMapperExample);
        } else {
            orderItems = new ArrayList<>();
        }
        // itemMap存放 商品id和库存 对应关系 的map
        HashMap<Long, Integer> itemMap = new HashMap<>();
        for (OrderItem orderItem : orderItems) {
            Long itemId = orderItem.getItemId();
            Integer num = orderItem.getNum();

            if (itemMap.size() != 0) {
                itemMap.put(itemId, num + (itemMap.get(itemId) == null ? 0 : itemMap.get(itemId)));
            } else {
                itemMap.put(itemId, num);
            }
        }

        // 扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            // productNum 不能超过限购数量
            // 还应该做检查该用户以前订单该商品购买数量，累计不能超过限购
            if (itemMap.size() != 0) {
                Stock selectStock = stockMapper.selectStock(productId);
                if (selectStock.getRestrictCount() < (productNum + ((itemMap.get(productId)) == null ? 0 : itemMap.get(productId)))) {
                    throw new BizException(OrderRetCode.PRODUCTNUM_OVER_LIMT.getCode(), OrderRetCode.PRODUCTNUM_OVER_LIMT.getMessage());
                }
            }


            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }


        return true;
    }
}